<template>
    <div class="index-container">
        <cbl-header></cbl-header>
        <cbl-user-info :userInfo="userInfo"></cbl-user-info>
        <div class="body-container">
            <div class="body-box flex">
                <cbl-body-left></cbl-body-left>
                <div class="center flex-1 custom-scrollbar">
                    <router-view></router-view>
                </div>
                <cbl-body-right :rankingList="rankingList"></cbl-body-right>
            </div>
        </div>
        <cbl-message-box :info="messageBoxInfo" @confirmClick="acceptChallenge"
                         @cancelClick="rejectChallenge"></cbl-message-box>
        <cbl-message-box :info="messageBoxMatchInfo" @confirmClick="continueChallenge"
                         @cancelClick="giveUpChallenge"></cbl-message-box>
    </div>
</template>

<script setup>
    import CblHeader from '@/components/CblHeader.vue';
    import CblUserInfo from '@/components/CblUserInfo.vue';
    import CblBodyLeft from '@/components/CblBodyLeft.vue';
    import CblBodyRight from '@/components/CblBodyRight.vue';
    import CblMessageBox from '@/components/CblMessageBox.vue';
    import {ref, reactive, getCurrentInstance, onMounted, onBeforeUnmount, computed} from 'vue';
    import {useStore} from 'vuex';
    import {useRouter} from 'vue-router';
    import {ElMessage} from 'element-plus';

    const {proxy} = getCurrentInstance();
    const router = useRouter();
    const userInfo = ref({});
    const rankingList = ref([]);
    const timer = ref(null);//计时器
    let times = ref(15);//倒计时15s
    let firstChallenge = ref('');//第一个挑战的用户
    const store = useStore();

    const inChess = computed(() => store.getters.getInChess);

    //弹框信息
    const messageBoxInfo = reactive({
        title: '挑战信息',
        content: `有人向您发起挑战，${times.value}s后自动关闭，默认拒绝挑战`,
        show: false,
        showCancelBtn: true,
        showConfirmBtn: true,
        cancelBtnText: '拒绝挑战',
        confirmBtnText: '接受挑战'
    });

    //弹框是否继续比赛
    const messageBoxMatchInfo = reactive({
        title: '比赛信息',
        content: `您有未完成的比赛`,
        show: false,
        showCancelBtn: true,
        showConfirmBtn: true,
        cancelBtnText: '认输',
        confirmBtnText: '继续比赛'
    });

    const socket = {
        //获取用户信息
        ownUserInfo(data) {
            userInfo.value = data;
        },
        //获取积分排行榜
        rankingList(data) {
            console.log(data);
            rankingList.value = data.data.list;
        },
        //收到挑战
        getChallenge(id) {
            if (!timer.value) {
                firstChallenge.value = id;
                messageBoxInfo.show = true;
                messageBoxInfo.content = `有人向您发起挑战，${times.value}s后自动关闭，默认拒绝挑战`;
                handleTimer();
            } else {
                proxy.$socket.io.emit('rejectChallenge', {toUserId: id, msg: '用户正在接受挑战，请稍后重新挑战'});
            }
        },
        //创建比赛
        async createMath(data) {
            if (data.code === 1) {
                await router.push('/index/chess');
            } else {
                ElMessage({
                    showClose: false,
                    message: data.msg,
                    type: 'error',
                });
            }
        },
        //查询是否有未完成的比赛
        checkMatch(data) {
            if (data.code === 0) {
                messageBoxMatchInfo.show = true;
            }
        },
        //放弃比赛
        giveUpChallenge() {
            proxy.$socket.io.emit('getOwnUserInfo');
            proxy.$socket.io.emit('getRankingList');
        }
    };

    onMounted(() => {
        proxy.$addSockets(socket, proxy);
        proxy.$socket.io.open();
        proxy.$socket.io.emit('login', store.getters.getUserInfo);
        proxy.$socket.io.emit('getOwnUserInfo');
        if (!inChess.value) {
            proxy.$socket.io.emit('checkMatch');
        }
        proxy.$socket.io.emit('getRankingList');
    });

    onBeforeUnmount(() => {
        proxy.$socket.io.emit('logout');
        proxy.$removeSockets(socket, proxy);
        proxy.$socket.io.close();
    });

    //处理计时器
    const handleTimer = () => {
        timer.value = window.setTimeout(function () {
            if (times.value <= 0) {
                times.value = 15;
                timer.value = null;
                messageBoxInfo.show = false;
                proxy.$socket.io.emit('rejectChallenge', {toUserId: firstChallenge.value, msg: '用户未接受挑战'});
            } else {
                times.value--;
                messageBoxInfo.content = `有人向您发起挑战，${times.value}s后自动关闭，默认拒绝挑战`;
                handleTimer();
            }
        }, 1000);
    };

    //接受挑战
    const acceptChallenge = () => {
        times.value = 15;
        window.clearTimeout(timer.value);
        timer.value = null;
        messageBoxInfo.show = false;
        proxy.$socket.io.emit('acceptChallenge', {toUserId: firstChallenge.value, msg: '用户接受挑战'});
    };
    //拒绝挑战
    const rejectChallenge = () => {
        times.value = 15;
        window.clearTimeout(timer.value);
        timer.value = null;
        messageBoxInfo.show = false;
        proxy.$socket.io.emit('rejectChallenge', {toUserId: firstChallenge.value, msg: '用户未接受挑战'});
    };
    //继续比赛
    const continueChallenge = async () => {
        messageBoxMatchInfo.show = false;
        await router.push('/index/chess');
    };
    //放弃比赛
    const giveUpChallenge = async () => {
        messageBoxMatchInfo.show = false;
        proxy.$socket.io.emit('giveUpChallenge');
    }

</script>

<style scoped lang="less">
    .index-container {
        height: 100%;
        min-height: 600px;
        background-image: url('../assets/bg.jpg');
        background-repeat: no-repeat;
        -webkit-background-size: cover;
        background-size: cover;
        background-position: center center;
        min-width: 1200px;

        .body-container {
            padding: 0 15px;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            height: calc(100% - 123px);

            .body-box {
                border: 3px solid rgba(155, 141, 128, 0.8);
                height: calc(100% - 6px);
                -webkit-border-radius: 5px;
                -moz-border-radius: 5px;
                border-radius: 5px;

                .center {
                    overflow: hidden;
                }
            }
        }
    }
</style>